<template>
	<view class="rebook">
		<view class="rebookBox" v-if="rebookTicket">
			<view class="oldTag">
				原航班
			</view>
			<view class="flightTime">
				{{rebookTicket.classDate}}
			</view>
			<view class="route-info">
				<view class="route-section">
					<text class="port-name">{{rebookTicket.startPortName}}</text>
					<text class="time">{{rebookTicket.departTime}}</text>
				</view>
				<view class="route-arrow">
					<view class="arrow-line"></view>
					<text class="ship-name">{{rebookTicket.shipName}}</text>
				</view>
				<view class="route-section">
					<text class="port-name">{{rebookTicket.arrivePortName}}</text>
					<text class="time">{{rebookTicket.arriveTime}}</text>
				</view>
			</view>
			<view class="userInfo">
				<view class="topInfo">
					<view class="name">
						<view>
							{{rebookTicket.passengerName}}
						</view>
						<view class="ticketType">
							{{rebookTicket.ticketTypeName}}
						</view>
					</view>
					<view class="price">
						￥<text class="priceText">{{rebookTicket.ticketPrice}}</text>
					</view>
				</view>
				<view class="cardId">
					{{rebookTicket.passengerCertNo}}
				</view>
				<view class="seat">
					{{rebookTicket.cabinName}}/{{rebookTicket.seatNo}}
				</view>
			</view>
		</view>

		<view class="rebookBox mt40" v-if="ticketInfo">
			<view class="oldTag">
				改签航班
			</view>
			<view class="flightTime">
				{{ticketInfo.departureDate}}
			</view>
			<view class="route-info">
				<view class="route-section">
					<text class="port-name">{{ticketInfo.departurePlace}}</text>
					<text class="time">{{ticketInfo.departureTime}}</text>
				</view>
				<view class="route-arrow">
					<view class="arrow-line"></view>
					<text class="ship-name">{{ticketInfo.shipName}}</text>
				</view>
				<view class="route-section">
					<text class="port-name">{{ticketInfo.arrivalPlace}}</text>
					<text class="time">{{ticketInfo.arrivalTime}}</text>
				</view>
			</view>
		</view>


		<button class="rebookBtn" @click="goRebookList">选择改签航班</button>
		<view class="agreement" @click="changeCheked">
			<uni-icons class="agreementIcon" v-if="checked" type="circle-filled" color="#55AAFF" size="26"></uni-icons>
			<uni-icons class="agreementIcon" v-else type="circle" color="#55AAFF" size="26"></uni-icons>
			<view class="agreementText">
				我已阅读
				<text class="blueText" @click.stop="viewAgreement(5778)">《改签须知》</text>
				，并同意条款
			</view>

		</view>

		<!-- 底部结算栏 -->
		<view class="bottom-bar" v-if="ticketInfo">
			<view class="price-section">
				<text class="price-label">{{ $t("ticket.booking.total") }}</text>
				<text class="total-price">¥{{ finalPayPrice }}</text>
			</view>
			<view class="detail-btn" @click="openDetailPopup">{{
		        $t("ticket.booking.details")
		      }}</view>
			<view class="submit-btn btn-enabled" @click="openRebookTips">
				提交订单
			</view>
		</view>


		<!-- 明细弹窗 -->
		<uni-popup ref="detailPopup" type="bottom">
			<view class="popup-content">
				<view class="popup-header">
					<text class="popup-title">{{
		    $t("ticket.booking.passengerTicketDetails")
		  }}</text>
					<text class="popup-close" @click="closeDetailPopup">×</text>
				</view>
				<view class="popup-body">
					<!-- 乘客详情 -->
					<view class="detail-passenger-item">
						<view class="detail-row">
							<text>{{ $t("ticket.booking.passengerName") }}：</text>{{ rebookTicket.passengerName }}
						</view>
						<view class="detail-row">
							<text>{{ $t("ticket.booking.idNumber") }}：</text>{{ rebookTicket.passengerCertNo  }}
						</view>

						<!-- 单程票显示 -->
						<view class="detail-row">
							<text>{{ $t("ticket.booking.ticketType") }}：</text>{{ rebookTicket.ticketTypeName || "—" }}

						</view>
					</view>

					<!-- 总计区域 -->
					<view class="detail-summary">
						<view class="summary-title">费用明细</view>
						<!-- 	<view class="summary-row" v-if="orderType === 1">
							<text>去程费用：</text>
							<text class="summary-price">¥{{ getGoTotalPrice().toFixed(2) }}</text>
						</view>
						<view class="summary-row" v-if="orderType === 1">
							<text>返程费用：</text>
							<text class="summary-price">¥{{ getBackTotalPrice().toFixed(2) }}</text>
						</view>
						<view class="summary-row" v-if="couponTotalDiscount > 0">
							<text>优惠券折扣：</text>
							<text class="discount-price">-¥{{ parseFloat(couponTotalDiscount).toFixed(2) }}</text>
						</view> -->
						<view class="summary-row total-summary">
							<text>应付金额：</text>
							<text class="total-summary-price">¥{{ finalPayPrice }}</text>
						</view>
					</view>
				</view>
			</view>
		</uni-popup>
		<uni-popup ref="rebookTips" type="center">
			<view class="tipsBox">
				<view class="title">
					温馨提示
				</view>
				<view class="content">
					<view class="item">
						您是否确认改签以下内容：
					</view>
					<view class="item">
						原航班信息：{{rebookTicket.classDate + ' ' + rebookTicket.departTime}}
					</view>
					<view class="item">
						改签后信息：{{ticketInfo.departureDate + ' ' + ticketInfo.departureTime}}
					</view>
					<view class="item">
						改签人数：1人
					</view>
					<view class="item">
						改签乘客：{{rebookTicket.passengerName}}
					</view>
					<view class="item">
						改签费用：{{finalPayPrice}}元
					</view>
					<view class="tipsText">
						信息核对无误后可点击“确认改签”按键完成改签。
					</view>
				</view>
				<view class="btnList">
					<view class="btn" @click="closeRebookTips">
						返回修改
					</view>
					<view class="btn define" @click="pay">
						确定改签
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		changeTicketOrder,
		getShipTicketInfo,
		getChangeTicketTotalFee
	} from "@/api/ws.js"
	export default {
		name: "rebook",
		data() {
			return {
				rebookTicket: '',
				// 航班和座位信息（通过onLoad参数赋值）
				ticketInfo: '',
				finalPayPrice: 0,
				changeRateAmount: 0, //手续费
				checked: false
			}
		},
		async onLoad(options) {
			// 解析路由参数
			console.log("options =>", options);
			this.rebookTicket = uni.getStorageSync('rebookTicket');
			await this.getTicketInfo()
			if (options && options.departureId) {
				// 单程或去程航班信息
				this.ticketInfo = {
					id: options.departureId || options.id || "",
					classNo: options.classNo || "",
					departurePlace: options.from ? decodeURIComponent(options.from) : "",
					arrivalPlace: options.to ? decodeURIComponent(options.to) : "",
					startPortId: options.startPortId ?
						decodeURIComponent(options.startPortId) : "",
					arrivePortId: options.arrivePortId ?
						decodeURIComponent(options.arrivePortId) : "",
					departureTime: options.departureTime ?
						decodeURIComponent(options.departureTime) : "",
					arrivalTime: options.arrivalTime ?
						decodeURIComponent(options.arrivalTime) : "",
					departureDate: options.departureDate || options.date || "",
					duration: options.duration ? decodeURIComponent(options.duration) : "",
					shipName: options.shipName ? decodeURIComponent(options.shipName) : "",
					seatType: options.seatType || "",
					cabinId: options.cabinId || "",
					cabinCode: options.cabinCode || "",
				};

				console.log("ticketInfo =>", this.ticketInfo);
				await this.getPrice();
			}



		},
		methods: {
			closeRebookTips() {
				this.$refs.rebookTips.close();
			},
			async getPrice() {
				try {
					let param = {
						"detailList": [{
							"arrivePortID": this.rebookTicket.arriveportid,
							"cabinID": this.ticketInfo.cabinId,
							"classID": this.ticketInfo.id,
							"oldTicketId": this.rebookTicket.ticketId,
							"startPortID": this.rebookTicket.startportid,
							"departDate": this.ticketInfo.departureDate + ' ' + this.ticketInfo
								.departureTime
						}],
						"oldOrderNo": this.rebookTicket.orderNo,
						"oldProductOrdersId": this.rebookTicket.orderId,
						"oldProductOrdersInfoId": this.rebookTicket.orderInfoId,
					}
					let res = await getChangeTicketTotalFee(param)
					if (res.code == 200) {
						this.changeRateAmount = res.result.feeDetails[0].changeRateAmount;
						this.finalPayPrice = res.result.totalRateAmount;
					}
					console.log("金额 res=>", res);
				} catch (e) {
					//TODO handle the exception
					uni.showToast({
						title: "获取金额失败",
						icon: 'none'
					});
				}
			},
			openRebookTips() {
				if (!this.checked) {
					uni.showToast({
						title: "请先勾选同意条款",
						icon: 'none'
					});
					return
				}
				this.$refs.rebookTips.open();
			},
			async getTicketInfo() {
				try {
					let param = {
						ticketID: this.rebookTicket.ticketId
					}
					let res = await getShipTicketInfo(param);
					console.log("船票信息 res=>", res);
					if (res.code == 200) {
						let data = {
							...this.rebookTicket,
							...res.result,

						}
						this.rebookTicket = data;
					}
				} catch (e) {
					uni.showToast({
						title: "获取船票数据失败",
						icon: 'none'
					});
				}

			},
			viewAgreement(id) {
				console.log("查看协议");
				uni.navigateTo({
					url: `/ticket_subpages/index/article?id=${id}`
				});
			},
			changeCheked() {
				this.checked = !this.checked;
			},
			openDetailPopup() {
				this.$refs.detailPopup.open();
			},
			closeDetailPopup() {
				this.$refs.detailPopup.close();
			},
			goRebookList() {
				const {
					classdate,
					arriveportid,
					startportid,
					cabinid
				} = this.rebookTicket;
				uni.navigateTo({
					url: `/ticket_subpages/index/rebookList?from=${startportid}&to=${arriveportid}&date=${classdate}&tripType=0&cabinid=${cabinid}`
				})
			},


			async pay() {

				try {

					let param = {
						"amount": this.finalPayPrice,
						"payMethod": "MP",
						"payPlatform": "WECHAT",
						"changeTicket": {
							"detailList": [{
								"arrivePortID": this.rebookTicket.arriveportid,
								"cabinID": this.ticketInfo.cabinId,
								"classID": this.ticketInfo.id,
								"oldTicketId": this.rebookTicket.ticketId,
								"startPortID": this.rebookTicket.startportid,
								"departDate": this.ticketInfo.departureDate + ' ' + this.ticketInfo
									.departureTime
							}],
							"oldOrderNo": this.rebookTicket.orderNo,
							"oldProductOrdersId": this.rebookTicket.orderId,
							"oldProductOrdersInfoId": this.rebookTicket.orderInfoId,
						}


					}
					let res = await changeTicketOrder(param)
					console.log("创建订单 res=>", res);
					if (res.code == 200) {
						if (res.result.amount === 0 && !res.result.pay) {
							uni.showLoading({
								title: '正在出票...'
							});
							setTimeout(() => {
								uni.hideLoading();
								uni.reLaunch({
									url: `/mall_subpages/order/details?id=${this.rebookTicket.orderId}`
								})
							}, 3000)
						} else {
							this.wxPay(res.result.pay)
						}

					} else {
						uni.showToast({
							title: res.message,
							icon: 'none'
						});
					}
				} catch (e) {
					//TODO handle the exception
					uni.showToast({
						title: "提交订单失败",
						icon: 'none'
					});
				}
			},
			wxPay(paymentParams) {
				let _this = this;
				// 调用微信支付
				uni.requestPayment({
					provider: 'wxpay',
					timeStamp: paymentParams.timeStamp,
					nonceStr: paymentParams.nonceStr,
					package: paymentParams.packageValue,
					signType: paymentParams.signType,
					paySign: paymentParams.paySign,
					success: () => {
						console.log("支付成功");

						uni.showLoading({
							title: '正在出票...'
						});
						setTimeout(() => {
							uni.hideLoading();
							uni.reLaunch({
								url: `/mall_subpages/order/details?id=${_this.rebookTicket.orderId}`
							})
						}, 3000)
					},
					fail: (err) => {
						_this.isLoading = false;
						uni.hideLoading();
						console.log('支付失败:', JSON.stringify(err));
						uni.showToast({
							title: _this.$t('payment.cancelled'),
							icon: 'none',
							duration: 2000
						});
					}
				});
			},
		}
	}
</script>

<style lang="scss">
	// 定义全局变量
	$primary-color: #498fff;
	$primary-gradient: linear-gradient(135deg, #498fff 0%, #3a7fe6 100%);
	$text-primary: #333;
	$text-secondary: #666;
	$text-light: #999;
	$background-light: #f5f5f5;
	$background-white: #fff;
	$border-radius: 12rpx;
	$padding-common: 30rpx;
	$margin-bottom: 20rpx;
	$font-small: 24rpx;
	$font-medium: 28rpx;
	$font-large: 32rpx;
	$font-xlarge: 36rpx;

	.rebook {
		width: 100%;
		min-height: 100vh;
		background-color: #F8F8F8;
		padding: 30rpx;
		box-sizing: border-box;

		.tipsBox {
			background-color: #fff;
			width: 90vw;
			border-radius: 20rpx;

			.title {
				font-size: 36rpx;
				font-weight: 600;
				padding: 40rpx;
				text-align: center;
			}

			.content {
				padding: 0 30rpx;
				width: 100%;
				box-sizing: border-box;

				.item {
					font-size: 30rpx;
					padding-bottom: 20rpx;
				}

				.tipsText {
					padding: 20rpx 0 40rpx;
				}
			}

			.btnList {
				display: flex;
				align-items: center;
				width: 100%;
				border-top: 2rpx solid #999;

				.btn {
					width: 50%;
					height: 100rpx;
					line-height: 100rpx;
					text-align: center;

					&.define {
						border-left: 2rpx solid #999;
						color: #2796ff;
					}
				}
			}
		}

		.agreement {
			width: 100%;
			display: flex;
			align-items: center;
			margin-top: 10rpx;

			.agreementIcon {
				margin-right: 10rpx;
				width: 10%;
			}

			.agreementText {
				display: flex;
				flex-wrap: wrap;
				width: 90%;
				font-size: 28rpx;
			}

			.blueText {
				color: #2796ff;
			}

			padding: 20rpx 0;
		}

		.rebookBox {
			width: 100%;
			background-color: #fff;
			border-radius: 20rpx;

			.oldTag {
				border-top-left-radius: 20rpx;
				border-bottom-right-radius: 20rpx;
				background-color: #E5F7FF;
				color: #5DC9E4;
				padding: 10rpx 14rpx;
				display: inline-block;
				font-size: 26rpx;
			}

			.flightTime {
				padding: 20rpx 30rpx 30rpx;
				font-size: 30rpx;
				border-bottom: 2rpx solid #eee;
			}

			.route-info {
				display: flex;
				align-items: center;
				// margin-bottom: 24rpx;
				padding: 30rpx;
				background-color: #fff;
				border-radius: 8rpx;
				border-bottom: 2rpx solid #eee;

				.route-section {
					display: flex;
					flex-direction: column;
					align-items: center;

					.port-name {
						font-size: 28rpx;
						font-weight: 600;
						color: #333;
						margin-bottom: 6rpx;
					}

					.time {
						font-size: 24rpx;
						color: #666;
					}
				}

				.route-arrow {
					flex: 1;
					display: flex;
					flex-direction: column;
					align-items: center;
					margin: 0 20rpx;

					.arrow-line {
						width: 100%;
						height: 2rpx;
						background: linear-gradient(to right, #498FFF, #5794ff);
						margin-bottom: 6rpx;
						position: relative;

						&::after {
							content: '';
							position: absolute;
							right: -6rpx;
							top: -4rpx;
							width: 0;
							height: 0;
							border-left: 8rpx solid #498FFF;
							border-top: 5rpx solid transparent;
							border-bottom: 5rpx solid transparent;
						}
					}

					.ship-name {
						font-size: 22rpx;
						color: #999;
						text-align: center;
					}
				}
			}

			.userInfo {
				width: 100%;
				box-sizing: border-box;
				padding: 30rpx;
				font-size: 28rpx;

				.topInfo {
					display: flex;
					justify-content: space-between;
					align-items: center;

					.name {
						font-size: 34rpx;
						display: flex;
						align-items: center;

						.ticketType {
							border: 2rpx solid #666;
							color: #666;
							border-radius: 20rpx;
							font-size: 22rpx;
							margin-left: 10rpx;
							padding: 2rpx 15rpx;
						}
					}

					.price {
						font-weight: 600;
						font-size: 26rpx;
						color: #ffaa00;

						.priceText {
							font-size: 36rpx;
						}
					}
				}

				.cardId {
					font-size: 28rpx;
					padding-top: 30rpx;
				}

				.seat {
					padding-top: 30rpx;
				}
			}
		}

		.rebookBtn {
			background-color: #55aaff;
			color: #fff;
			margin-top: 50rpx;
			border-radius: 40rpx;
		}

		// 底部结算栏
		.bottom-bar {
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			display: flex;
			justify-content: space-between;
			align-items: center;
			height: 100rpx;
			background-color: $background-white;
			padding: 0 $padding-common;
			border-top: 1rpx solid #eee;
			z-index: 11;

			.price-section {
				display: flex;
				align-items: baseline;

				.price-label {
					font-size: $font-medium;
					color: $text-secondary;
					margin-right: 10rpx;
				}

				.total-price {
					font-size: $font-xlarge;
					font-weight: bold;
					color: #ff5233;
				}
			}

			.detail-btn {
				margin-left: 20rpx;
				margin-right: 20rpx;
				padding: 10rpx 30rpx;
				background: #f5f5f5;
				color: #498fff;
				border-radius: 30rpx;
				font-size: 28rpx;
				font-weight: 500;
				align-self: center;
			}

			.submit-btn {
				width: 240rpx;
				height: 80rpx;
				background-color: #ccc;
				border-radius: 40rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				color: #fff;

				text {
					color: $background-white;
					font-size: $font-medium;
					font-weight: bold;
				}

				&.btn-enabled {
					background-color: $primary-color;
				}

				&.btn-submitting {
					background-color: #9fb8e0;
					/* 淡蓝色表示提交中 */
					position: relative;

					&:after {
						content: "";
						position: absolute;
						left: 15rpx;
						top: 50%;
						transform: translateY(-50%);
						width: 24rpx;
						height: 24rpx;
						border: 3rpx solid rgba(255, 255, 255, 0.5);
						border-top-color: #fff;
						border-radius: 50%;
						animation: spin 1s linear infinite;
					}
				}
			}
		}

		.detail-summary {
			background: #fff;
			border-radius: 12rpx;
			padding: 24rpx;
			margin-top: 20rpx;
			border: 1rpx solid #f0f0f0;

			.summary-title {
				font-size: 32rpx;
				font-weight: 600;
				color: #333;
				margin-bottom: 16rpx;
				text-align: center;
			}

			.summary-row {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 12rpx 0;
				font-size: 28rpx;
				color: #666;

				.summary-price {
					color: #498fff;
					font-weight: 500;
				}

				.discount-price {
					color: #ff5233;
					font-weight: 500;
				}

				&.total-summary {
					margin-top: 16rpx;
					padding-top: 16rpx;
					border-top: 2rpx solid #f0f0f0;
					font-size: 32rpx;
					font-weight: 600;
					color: #333;

					.total-summary-price {
						color: #ff5233;
						font-size: 36rpx;
						font-weight: bold;
					}
				}
			}
		}

		// 弹窗样式
		.popup-content {
			background-color: $background-white;
			border-top-left-radius: 20rpx;
			border-top-right-radius: 20rpx;
			overflow: hidden;
			max-height: 80vh;

			.popup-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 30rpx;
				border-bottom: 1rpx solid #eee;

				.popup-title {
					font-size: $font-large;
					font-weight: 500;
					color: $text-primary;
				}

				.popup-close {
					font-size: 40rpx;
					color: $text-light;
					width: 60rpx;
					height: 60rpx;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}

			.popup-body {
				max-height: calc(80vh - 100rpx);
				overflow-y: auto;
				padding: 30rpx;
			}
		}


	}
</style>